package com.calc;

import java.text.MessageFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.calc.adapter.ImageTextGridViewAdapter;
import com.calc.setting.SettingActivity;
import com.calc.utils.ActivityUtils;
import com.calc.utils.AppExitUtils;

public class StartActivity extends Activity {

    private static final String TAG = "StartActivity";

    public static boolean isFirst = true;

//    private Button generalCalculator,binaryChange;

    private Vibrator vibrator;

    private int[] icons={R.drawable.junior_calculator, R.drawable.senior_calculator,R.drawable.measure_length,
            R.drawable.measure_area,R.drawable.loan,
            R.drawable.imcome_tax,R.drawable.exchange,R.drawable.binary};
    private int[] items={R.string.app_junior_calc, R.string.app_senior_calc, R.string.app_length_calc,
            R.string.app_area_calc, R.string.app_loan_calc,
            R.string.app_tax_calc, R.string.app_exchange_rate, R.string.app_binary_calc};

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        AppExitUtils.setCurrentActivity(this);
        AppExitUtils.addActivity(this);

        //添加计算器组件
        ImageTextGridViewAdapter adapter = new ImageTextGridViewAdapter(this, items, icons);
        GridView mainGridView = ((GridView)findViewById(R.id.main_grid_view));
        mainGridView.setAdapter(adapter);
        mainGridView.setOnTouchListener(ActivityUtils.getButtonVibratorListener(StartActivity.this,true));
        mainGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "view.getId()="+view.getId()+",position="+position+",id="+id);
                Intent intent = new Intent();
                switch (position){
                    case 0:
                        //简易计算器
                        intent.setClass(StartActivity.this,SeniorCalcActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        //高级计算器
                        intent.setClass(StartActivity.this,SeniorCalcActivity.class);
                        startActivity(intent);
                        break;
                    case 2:
                        //长度计算器
                        intent.setClass(StartActivity.this,LengthCalcActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        //面积计算器
                        intent.setClass(StartActivity.this, AreaCalcActivity.class);
                        startActivity(intent);
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                    case 6:
                        break;
                    default:
                        break;
                }
            }
        });
        //判断是否是第一次进入本软件，如果是则从配置文件中读取默认首页
        if(isFirst) {
            Log.v(TAG, "isFirst="+isFirst);
            isFirst = false;
            Intent intent = new Intent();
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            String start = sp.getString("app_component_list",getResources().getString(R.string.app_index_value));
            Log.v(TAG, "app_component_list="+start);
            switch (Integer.parseInt(start)) {
                case 0:
                    return ;
                case 1:
                    intent.setClass(StartActivity.this,SeniorCalcActivity.class);
                    break;
                case 2:
                    intent.setClass(StartActivity.this,LengthCalcActivity.class);
                    break;
                case 3:
                    intent.setClass(StartActivity.this,AreaCalcActivity.class);
                    break;
                case 4:
                    intent.setClass(StartActivity.this,SeniorCalcActivity.class);
                    break;
                case 5:
                    intent.setClass(StartActivity.this,SeniorCalcActivity.class);
                    break;
                case 6:
                    intent.setClass(StartActivity.this,SeniorCalcActivity.class);
                    break;
                default:
                    return ;
            }
            startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
        case R.id.menu_setting:
            showSetting();
            break;
        case R.id.menu_help :
            showHelp();
            break;
        case R.id.menu_exit:
            AppExitUtils.showExitTips(StartActivity.this);
            break;
        case R.id.menu_about:
            showAbout();
            break;
        case R.id.menu_contact:
            showContact();
            break;
        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示帮助
     */
    private void showHelp() {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * 显示关于对话框
     */
    private void showAbout() {
        AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
        LayoutInflater layoutInflater = (LayoutInflater)StartActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View aboutView = layoutInflater.inflate(R.layout.about, null);
        //---->start 开始处理版本号信息
        TextView versionTextView = (TextView)aboutView.findViewById(R.id.soft_version);
        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(new ComponentName(this,getClass()).getPackageName(), 0) ;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String softVersion = packageInfo.versionName;
        String versionText = versionTextView.getText().toString();
        String deviceModel = Build.MODEL; // 设备型号
        String versionRelease = Build.VERSION.RELEASE; // 设备的系统版本
        versionText = MessageFormat.format(versionText, deviceModel + " " + versionRelease, softVersion);
        Log.d(TAG, versionText);
        versionTextView.setText(versionText);
        //---->end 版本号信息处理完毕
        builder.setView(aboutView);
        builder.setPositiveButton(R.string.i_know, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    /**
     * 显示联系作者
     */
    private void showContact() {
        AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
        LayoutInflater layoutInflater = (LayoutInflater)StartActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contactView = layoutInflater.inflate(R.layout.contact, null);
        builder.setView(contactView);
        builder.setNegativeButton(R.string.i_know, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    /**
     * 显示喜好设置
     */
    private void showSetting() {
        Intent settingIntent = new Intent(StartActivity.this, SettingActivity.class);
        startActivity(settingIntent);
    }

    @Override
    protected void onDestroy() {
        AppExitUtils.removeActivity(this);
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        if(vibrator!=null) {
            vibrator.cancel();
        }
        super.onStop();
    }

    //按两次返回键退出程序
    private static Boolean isExit = false;
    private static Boolean hasTask = false;
    Timer tExit = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            isExit = false;
            hasTask = true;
        }
    };
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(!isExit) {
                isExit = true;
                Toast.makeText(StartActivity.this, R.string.double_back_exit, Toast.LENGTH_SHORT).show();
                if(!hasTask) {
                    tExit.schedule(task, 2000);
                }
            } else {
                AppExitUtils.exit((ActivityManager)StartActivity.this.getSystemService(Context.ACTIVITY_SERVICE),StartActivity.this.getPackageName());
            }
        }
        return false;
    }
}